//
//  LDNewFeatureController.swift
//  Weibo201655
//
//  Created by pro on 16/5/6.
//  Copyright © 2016年 LeeDan. All rights reserved.
//

import UIKit

private let itemCount = 4
private let cellID = "newFeatureCell"
class LDNewFeatureController: UICollectionViewController {

    init () {
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //注册cell
        collectionView?.registerClass(LDNewCell.self, forCellWithReuseIdentifier: cellID)
        
        //翻页
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension LDNewFeatureController {
    //MARK: collectionView 数据源  代理
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return itemCount
    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as! LDNewCell
        cell.itemIndex = indexPath.item
        return cell
        
    }
    
    //执行按钮动画
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        //获取索引
        let index = Int(scrollView.contentOffset.x / scrollView.frame.width)
        
        //判断是不是最后一页
        if index == itemCount - 1 {
            //获取cell
            let indexPath = NSIndexPath(forItem: index, inSection: 0)
            let cell = collectionView?.cellForItemAtIndexPath(indexPath) as! LDNewCell
            //执行动画
            cell.startButtonAnimation()
        }
    }
    
}

//MARK: 自定义cell
class LDNewCell: UICollectionViewCell {
    
    //MARK: 索引属性，根据索引拼接图片名
    var itemIndex: Int = 0 {
        didSet {
            imgView.image = UIImage(named: "new_feature_\(itemIndex + 1)")
        }
    }
    
    
    //按钮弹出动画
    private func startButtonAnimation() {
        //显示按钮
        startButton.hidden = false
        //开始动画
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        UIView.animateWithDuration(0.6, delay: 0.1, usingSpringWithDamping: 0.4, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                print("新特性：开始按钮弹出动画完成")
        }
    }
    
    //MARK:  startButton点击事件
    func startButtonClick() {
        
        //切换控制器
        NSNotificationCenter.defaultCenter().postNotificationName(LDSwitchRootViewControllerNotification, object: true)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(imgView)
        contentView.addSubview(startButton)
        
        imgView.translatesAutoresizingMaskIntoConstraints = false
        startButton.translatesAutoresizingMaskIntoConstraints = false
        //约束
        //imgView
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[imgView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["imgView": imgView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[imgView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["imgView": imgView]))
        //startButton
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0))
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -100))
    }
    
    //MARK: lazy
    lazy var imgView: UIImageView = UIImageView(image: UIImage(named: "new_feature_1"))
    lazy var startButton: UIButton = {
    
        let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        
        btn.addTarget(self, action: "startButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        //隐藏按钮
        btn.hidden = true
        
        btn.sizeToFit()
        return btn
    }()
    
}